package com.ihighest.app.infox.activity;

import io.rong.imkit.RongIM;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.DataCacheTools;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.SettingCheckboxView;
import com.umeng.message.PushAgent;
import com.umeng.update.UmengDialogButtonListener;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

public class SettingActivity extends BaseActivity implements OnClickListener {

	final static String TAG = "SettingActivity";

	private ActivityTitle settingTitle;
	private SettingCheckboxView nightStyle, slidingChangePager, wifi, receiveNotification, WhenTheSubscriptionShare, PayAttentionToShare,
			WhenCollectionShare, WhenAssessmentShare;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_setting);

		initVIew();
		// Constants.changeSize(SettingActivity.this, this, true);
		settingTitle.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (settingTitle.rightText.getText().toString().equals("注销")) {
					new AlertDialog.Builder(SettingActivity.this).setMessage("您确定要退出当前用户吗")// 设置显示的内容

							.setPositiveButton("确定", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									// 确定按钮的响应事件

									loginOut();
								}

							}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {

								}

							}).show();// 在按键响应事件中显示此对话框

				} else if (settingTitle.rightText.getText().toString().equals("登录")) {
					Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
					startActivity(intent);
				}

			}

		});
	}

	/**
	 * 退出登录
	 * 
	 * 
	 * @author lkx Created at 2015-11-16 下午5:30:05
	 */
	private void loginOut() {
		final String uid = SharedPreferencesKit.getString(SettingActivity.this, Const.SP_KEY_USER_ID);
		final String mid = SharedPreferencesKit.getString(SettingActivity.this, Const.SP_KEY_USER_MID);
		Api.post("logout", ApiParam.create().addParam("uid", uid), new ApiCallback(SettingActivity.this) {

			@Override
			public void handleSuccess(ApiResult result) {
				settingTitle.setRightTextViewText("登录");

				new Thread(new Runnable() {

					@Override
					public void run() {
						try {
							// 断开聊天链接
							// RongIM.getInstance().disconnect();
							RongIM.getInstance().logout();
							// Umeng Push
							PushAgent.getInstance(getApplicationContext()).removeAlias(uid, "AID");
							PushAgent.getInstance(getApplicationContext()).removeAlias(mid, "MID");
							AppKit.cleanUserInfo(getApplicationContext());

						} catch (Exception ex) {
							Log.e(TAG, ex.getMessage(), ex);
						}

					}
				}).start();
				// Intent mIntent = new
				// Intent(Const.FINISHLOGIN);
				// // 发送广播
				// sendBroadcast(mIntent);
			}

			@Override
			public void handleFailure(Exception e, String msg) {
			}
		}, SettingActivity.this);
	}

	/**
	 * 初始化绑定控件
	 * 
	 * 
	 * @author lkx Created at 2015-10-5 下午7:11:37
	 */
	private void initVIew() {
		settingTitle = (ActivityTitle) findViewById(R.id.infox_settingTitle);
		settingTitle.setTitle("设置");
		settingTitle.setViewVersible(settingTitle.titleBack, settingTitle.rightText);
		settingTitle.setViewGone(settingTitle.titleMsg, settingTitle.titleRefresh);
		if (TextUtils.isEmpty(SharedPreferencesKit.getString(SettingActivity.this, Const.SP_KEY_USER_ID))) {
			settingTitle.setRightTextViewText("登录");
		} else {
			settingTitle.setRightTextViewText("注销");
		}

		nightStyle = (SettingCheckboxView) findViewById(R.id.indox_setting_nightStyle);
		slidingChangePager = (SettingCheckboxView) findViewById(R.id.indox_setting_slidingChangePager);
		wifi = (SettingCheckboxView) findViewById(R.id.indox_setting_wifi);
		receiveNotification = (SettingCheckboxView) findViewById(R.id.indox_setting_receiveNotification);
		WhenTheSubscriptionShare = (SettingCheckboxView) findViewById(R.id.indox_setting_WhenTheSubscriptionShare);
		PayAttentionToShare = (SettingCheckboxView) findViewById(R.id.indox_setting_PayAttentionToShare);
		WhenCollectionShare = (SettingCheckboxView) findViewById(R.id.indox_setting_WhenCollectionShare);
		WhenAssessmentShare = (SettingCheckboxView) findViewById(R.id.indox_setting_WhenAssessmentShare);
		// findViewById(R.id.editInfo).setOnClickListener(this);
		findViewById(R.id.editPsd).setOnClickListener(this);
		findViewById(R.id.setTextSize).setOnClickListener(this);
		findViewById(R.id.indox_setting_clearData).setOnClickListener(this);
		findViewById(R.id.indox_setting_version).setOnClickListener(this);
		findViewById(R.id.indox_setting_aboutInfox).setOnClickListener(this);

		setCheckBoxListener();
		nightStyle.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_NIGHTStyle));
		slidingChangePager.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_SLIDINGCHANGEPAGER));
		wifi.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_WHEN_WIFI_SHOWIMG));
		receiveNotification.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_ACCEPTINFOMATION));
		WhenTheSubscriptionShare.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_DINGYUE_SHARE));
		PayAttentionToShare.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_PAYATTENTIONSHARE));
		WhenCollectionShare.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_COLLECTIONSHARE));
		WhenAssessmentShare.setChecked(SharedPreferencesKit.getBoolean(SettingActivity.this, Const.SP_ASSESSMENTSHARE));

	}

	/**
	 * 设置checkbox监听
	 * 
	 * 
	 * @author lkx Created at 2015-10-6 上午10:39:16
	 */
	private void setCheckBoxListener() {
		nightStyle.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_NIGHTStyle, arg1);
				commitSettingData(Const.SP_NIGHTStyle, arg1);
			}
		});
		slidingChangePager.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_SLIDINGCHANGEPAGER, arg1);
				commitSettingData(Const.SP_SLIDINGCHANGEPAGER, arg1);
			}
		});
		wifi.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_WHEN_WIFI_SHOWIMG, arg1);
				commitSettingData(Const.SP_WHEN_WIFI_SHOWIMG, arg1);
			}
		});
		receiveNotification.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				System.out.println("监听");
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_ACCEPTINFOMATION, arg1);
				if (SharedPreferencesKit.getBoolean(getApplicationContext(), Const.SP_ACCEPTINFOMATION, true)) {
					PushAgent.getInstance(getApplicationContext()).enable();
				} else {
					PushAgent.getInstance(getApplicationContext()).disable();
				}
				commitSettingData(Const.SP_ACCEPTINFOMATION, arg1);
			}
		});
		WhenTheSubscriptionShare.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_DINGYUE_SHARE, arg1);
				commitSettingData(Const.SP_DINGYUE_SHARE, arg1);
			}
		});
		PayAttentionToShare.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_PAYATTENTIONSHARE, arg1);
				commitSettingData(Const.SP_PAYATTENTIONSHARE, arg1);
			}
		});
		WhenCollectionShare.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_COLLECTIONSHARE, arg1);
				commitSettingData(Const.SP_COLLECTIONSHARE, arg1);
			}
		});
		WhenAssessmentShare.setOnclickedListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				SharedPreferencesKit.putBoolean(SettingActivity.this, Const.SP_ASSESSMENTSHARE, arg1);
				commitSettingData(Const.SP_ASSESSMENTSHARE, arg1);
			}

		});
	}

	@Override
	public void onClick(View view) {
		Intent intent = null;
		switch (view.getId()) {
		// case R.id.editInfo:
		// if (TextUtils.isEmpty(SharedPreferencesKit.getString(this,
		// Const.SP_KEY_USER_ID))) {
		// intent = new Intent(this, LoginActivity.class);
		// ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
		// startActivity(intent);
		// } else {
		// intent = new Intent(SettingActivity.this, AlertInfoActivity.class);
		// startActivity(intent);
		// }
		// break;
		case R.id.editPsd:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
				intent = new Intent(this, LoginActivity.class);
				ToastKit.showShort(this, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				intent = new Intent(SettingActivity.this, ChangePasswordActivity.class);
				startActivity(intent);
			}
			break;
		case R.id.setTextSize:
			intent = new Intent(SettingActivity.this, TextSizeActivity.class);
			startActivity(intent);
			break;
		case R.id.indox_setting_clearData:
			AppKit.cleanCache(this);
			ToastKit.showShort(this, "已清除缓存");
			getSharedPreferences(DataCacheTools.PREFERENCE_NAME, 0).edit().clear().commit();
			break;
		case R.id.indox_setting_version:
			UmengUpdateAgent.setUpdateOnlyWifi(false);// 非wifi下也能更新
			UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {

				@Override
				public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
					switch (updateStatus) {
					case UpdateStatus.Yes: // has update
						UmengUpdateAgent.showUpdateDialog(getApplicationContext(), updateInfo);
						UmengUpdateAgent.setDialogListener(new UmengDialogButtonListener() {

							@Override
							public void onClick(int status) {
								switch (status) {
								case UpdateStatus.Update:
									SharedPreferencesKit.putBoolean(getApplicationContext(), Const.SP_FIRSTOPEN, false);
									break;
								case UpdateStatus.Ignore:
									break;
								case UpdateStatus.NotNow:
									break;
								}
							}
						});
						break;
					case UpdateStatus.No: // has no update
						ToastKit.showShort(getApplicationContext(), "当前已经是最新版本");
						break;
					case UpdateStatus.NoneWifi: // none wifi
						ToastKit.showShort(getApplicationContext(), "当前没有Wifi连接，请在Wifi环境下进行更新");
						break;
					case UpdateStatus.Timeout: // time out
						ToastKit.showShort(getApplicationContext(), "检测更新超时，请查看当前网络是否正常");
						break;
					}
				}
			});
			UmengUpdateAgent.forceUpdate(getApplicationContext());
			break;
		case R.id.indox_setting_aboutInfox:
			intent = new Intent(SettingActivity.this, AboutActivity.class);
			startActivity(intent);

			break;

		default:
			break;
		}

	}

	@Override
	protected void onResume() {
		initVIew();
		super.onResume();
	}

	/**
	 * 提交设置信息
	 * 
	 * @param spAssessmentshare
	 *            设置项
	 * @param arg1
	 *            是否开启
	 * 
	 * @author lkx Created at 2015-10-30 下午2:17:22
	 */
	private void commitSettingData(String spAssessmentshare, boolean arg1) {
		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(SettingActivity.this, Const.SP_KEY_USER_ID))) {
			// 如果用户已经登录，将设置信息提交
			Api.post("me/setting", ApiParam.create().addParam("key", spAssessmentshare).addParam("value", String.valueOf(arg1)),
					new ApiCallback(SettingActivity.this, true) {

						@Override
						public void handleSuccess(ApiResult result) {

						}

						@Override
						public void handleFailure(Exception e, String msg) {

						}
					}, SettingActivity.this);
		} else {
			// ToastKit.showShort(this, "您当前尚未登录，设置信息无法同步");
		}

	}
}
